/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlets.patient.measurement;

import be.ugent.medirem.logic.MeasurementRemote;
import be.ugent.medirem.logic.PatientRemote;
import be.ugent.medirem.persistence.entity.details.MeasurementTypeDetails;
import be.ugent.medirem.persistence.entity.values.MeasurementValues;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Simon
 */
public class AddMeasurementServlet extends HttpServlet {
    @EJB
    private PatientRemote patientBean;
    @EJB
    private MeasurementRemote measurementBean;


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        List<MeasurementTypeDetails> list = measurementBean.getAllMeasurementTypes();

        request.setAttribute("types", list);
        
        request.getRequestDispatcher("/patient/measurement/add.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        MeasurementValues m = (MeasurementValues) request.getAttribute("measurement");

        boolean validate = true;
        if (m == null)
            validate = false;
        else {
            if (m.getTypeId() == null)
                validate = false;
            if (m.getValue() <= 0.0)
                validate = false;
        }

        // Validation OKAY
        if (validate) {
            m.setDateTaken(new Date());
            String username = request.getUserPrincipal().getName();
            Long id = patientBean.getPatientId(username);
            measurementBean.addMeasurement(id, m);
            request.getSession().setAttribute("flash","Measurement added");
            response.sendRedirect(request.getContextPath()+"/patient/measurement/list");
        }
        // Validation NOT OKAY
        else {
            request.getSession().setAttribute("flash","Validation error");
            doGet(request, response);
        }

    }

}
